﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Zsnd.Helpers;
using MaymuseMS.DAO;
using MaymuseMS.DAL;
using MaymuseMS.Models;
using MaymuseMS.Models.ValueObject;
using DoddleReport;
using DoddleReport.Web;

namespace MaymuseMS.Controllers {
    public abstract class ReportController<TEntity> : GenericController where TEntity : class, new() {
        protected abstract GenericRepository<TEntity> GenericRepository { get; }

        //protected abstract Expression<Func<TEntity, int>> Predicates { get; }

        protected virtual ReportHelper<TEntity> ReportHelper() {
            return new ReportHelper<TEntity> {
                Footer = "Copyright 2011 &copy; 美淼信息"
            };
        }
        protected abstract IEnumerable<object> Get(IEnumerable<TEntity> entities);
        protected abstract IEnumerable<object> Reports(IEnumerable<TEntity> entities);
        //默认不求和
        protected virtual object UserData(DAO<TEntity> dao) {
            return null;
        }

        public ReportResult Report() {
            JQGridParm parm = (JQGridParm)Session[Ctrl];
            if (parm != null) {
                var dao = new DAO<TEntity>(parm, GenericRepository);
                var entities = dao.Query.ToList();
                if (entities != null) {
                    var report = new Report(Reports(entities).ToReportSource());
                    string[] s = ReportHelper().Fields;
                    int i = 0;
                    foreach (var d in report.DataFields) {
                        d.HeaderText = s[i++];
                    }
                    report.TextFields.Title = ReportHelper().Title;
                    report.TextFields.SubTitle = ReportHelper().SubTitle;
                    report.TextFields.Footer = ReportHelper().Footer;
                    report.TextFields.Header = string.Format(@"
                    报告生成日期: {0}
                    总项目数: {1}
                    总数量: {2}", DateTime.Now, entities.Count(), entities.Sum(ReportHelper().Predicate));
                    //utf-8 带bom
                    Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });
                    return new ReportResult(report);
                }
            }
            return null;
        }

        [HttpPost]
        public ActionResult Index(JQGridParm parm) {
            var dao = new DAO<TEntity>(parm, GenericRepository);
            var entities = dao.Enums;

            var userData = UserData(dao);

            var jsonData = dao.GetData(Get(entities), userData);

            Session[Ctrl] = parm;

            return Json2(jsonData);
        }
    }
}
